package com.example.mobifin_busticket.views.activities;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.BusTicketManagaer;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.R.id;
import com.example.mobifin_busticket.R.layout;
import com.example.mobifin_busticket.R.menu;
import com.example.mobifin_busticket.UserInfo;
import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.models.BusModel;
import com.example.mobifin_busticket.models.PassengerDetails;
import com.example.mobifin_busticket.models.TicketDetailsModel;
import com.google.common.io.LineReader;

import android.support.v7.app.ActionBarActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class PinConformActivity extends MobifinActivity implements
		android.view.View.OnClickListener {
	ArrayList<Integer> fareList;
	String source, destination, doj, travelBoardingPoint, totalSeat, strJSON;
	int totalTraveller;
	EditText etTransactionPin;
	TextView tvRoute, tvfare, tvTravelBoardingName, tvTotalPerson,
			tvTravellerName;
	Button btn_requestPayment, btn_headerBck;
	PassengerDetails passengerModel;
	LinearLayout ll_passengerDetails, llError, llChildError;
	View contactView;
	UserInfo userInfo = new UserInfo();
	double cntFare = 0;
	String blockKeytoConfirm;
	String tinForMobifin;
	Object ticketDetails;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pin_conform);
		passengerModel = new PassengerDetails();

		ll_passengerDetails = (LinearLayout) findViewById(R.id.llDynamicPersonDetails);
		llError = (LinearLayout) findViewById(R.id.llChildError);
		llChildError = (LinearLayout) findViewById(R.id.llChildError);
		etTransactionPin = (EditText) findViewById(R.id.etTransactionPin);
		btn_requestPayment = (Button) findViewById(R.id.btn_RequestPayment);
		btn_headerBck = (Button) findViewById(R.id.headerBckButton);
		tvRoute = (TextView) findViewById(R.id.tvSrcToRoute);
		tvfare = (TextView) findViewById(R.id.tvTotal_fare);
		tvTravelBoardingName = (TextView) findViewById(R.id.tvTravelName);
		tvTotalPerson = (TextView) findViewById(R.id.tvTotalPerson);
		btn_requestPayment.setOnClickListener(this);
		btn_headerBck.setOnClickListener(this);
		llError.setOnClickListener(this);
		fareList = new ArrayList<Integer>();
		fareList = getIntent().getIntegerArrayListExtra("fare");
		source = getIntent().getStringExtra("source");
		destination = getIntent().getStringExtra("destination");
		doj = getIntent().getStringExtra("doj");
		totalSeat = getIntent().getStringExtra("TotalSeat");
		travelBoardingPoint = AppData.TravelBoarding;

		for (int i = 0; i < fareList.size(); i++) {
			cntFare = cntFare + fareList.get(i);
			tvfare.setText("INR:" + "" + cntFare);
			System.out.println("total fare:" + cntFare);
		}

		tvRoute.setText(source + " " + "to " + destination + " " + doj);
		tvTravelBoardingName.setText(travelBoardingPoint);
		tvTotalPerson.setText(totalSeat + " " + "person travelling");
		btn_requestPayment.setText(getResources().getString(
				R.string.btn_requestPayment)
				+ " " + "(" + tvfare.getText() + ")");
		passengerModel = AppData.PassengerModel;
		userInfo = AppData.getUserInfo();
		passengerModel.toJSON(passengerModel);
		strJSON = passengerModel.getstrJSON();
		totalTraveller = passengerModel.getpassengerList().size();
		System.out.println("Total passenger :" + totalTraveller);
		init();
	}

	private void init() {
		// TODO Auto-generated method stub

		for (int i = 0; i < passengerModel.getpassengerList().size(); i++) {

			if (!passengerModel.getpassengerList().isEmpty()) {
				tvTravellerName = new TextView(PinConformActivity.this);
				tvTravellerName.setText(passengerModel.getpassengerList()
						.get(i).getTitle()
						+ "."
						+ " "
						+ passengerModel.getpassengerList().get(i)
								.gettravellerName()
						+ ", "
						+ passengerModel.getpassengerList().get(i).getage()
						+ " year");
				if (passengerModel.getpassengerList().get(i).getTitle() == "MR") {
					tvTravellerName.setCompoundDrawablesWithIntrinsicBounds(
							R.drawable.male, 0, 0, 0);
				} else
					tvTravellerName.setCompoundDrawablesWithIntrinsicBounds(
							R.drawable.female, 0, 0, 0);
				tvTravellerName.setPadding(3, 3, 3, 3);
				tvTravellerName.setCompoundDrawablePadding(5);
				tvTravellerName.setTextColor(Color.BLACK);
				ll_passengerDetails.addView(tvTravellerName);
			}

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_RequestPayment:
			onClickRequestPayment();
			break;
		case R.id.headerBckButton:
			finish();
			break;
		default:
			break;
		}
	}

	private void onClickRequestPayment() {
		// TODO Auto-generated method stub
		if (userInfo.getTransactionPassword().toString()
				.equals(etTransactionPin.getText().toString().trim())) {
			sendJSON();
		} else {
			Toast.makeText(this, "Please enter valid transaction pin", 1000)
					.show();
		}
	}

	final ResponseListener resonseFromServer = new ResponseListener() {

		@Override
		public void onResponse(Object blockKeyresonse) {
			// printData(busListresonse);
			String[] strBlockkey = blockKeyresonse.toString().split(";");
			System.out.println("Response:" + strBlockkey);
			if (blockKeyresonse == null) {

			} else {
				blockKeytoConfirm = strBlockkey[1].toString();
				deductBalance(strJSON, totalTraveller, cntFare,
						strBlockkey[1].toString());
			}
		}
	};

	private void sendJSON() {
		// TODO Auto-generated method stub

		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager.setJSONObj(PinConformActivity.this, resonseFromServer,
				AppData.CONSUMERKEY, AppData.SECRETKEY, AppData.BASESEATURL
						+ "/blockTicket", strJSON, "BlockTicket");

	}

	ResponseListener mobifindeductBalanceResponseListenrer = new ResponseListener() {

		@Override
		public void onResponse(Object object) {
			// TODO Auto-generated method stub
			//
			System.out
					.println("----Response Received in pinconfirem activity\n"
							+ (String) object);

			try {
				JSONObject mobifinResponse = new JSONObject((String) object);
				String responseCode, responseDesc;
				responseCode = mobifinResponse.getString("ResponseCode");
				responseDesc = mobifinResponse.getString("ResponseDescription");
				if (responseCode.equals("000")
						&& responseDesc.equals("Successful")) {

					// getTicketDetails("KHNA6DV");
					confirmTicketWithSeatSeller(blockKeytoConfirm);

				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	protected void deductBalance(String passengerJSON, int no_of_passenger,
			double cntFare, String strBlockkey) {
		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager.deductResellerBalance(this, passengerJSON,
				no_of_passenger, cntFare * 100, strBlockkey,
				mobifindeductBalanceResponseListenrer);

	}

	protected void confirmTicketWithSeatSeller(String blockKey) {
		// TODO Auto-generated method stub
		ResponseListener ticketNoResponseFromSeatSeller = new ResponseListener() {
			@Override
			public void onResponse(Object objTicketNo) {
				// TODO Auto-generated method stub

				tinForMobifin = (String) objTicketNo;
				System.out.println("Ticket no:" + tinForMobifin);
				getTicketDetails(objTicketNo);

			}
		};
		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager.getTicketNoFromSeatSeler(PinConformActivity.this,
				ticketNoResponseFromSeatSeller, AppData.CONSUMERKEY,
				AppData.SECRETKEY, AppData.BASESEATURL
						+ "/bookticket?blockKey=" + blockKey, "TicketNo");
	}

	protected void getTicketDetails(Object objTicketNo) {
		ResponseListener ticketDetailsResponseFromSeatSeller = new ResponseListener() {
			@Override
			public void onResponse(Object objTicketDetails) {
				// TODO Auto-generated method stub
				ArrayList<TicketDetailsModel> ticketDetailsList = (ArrayList<TicketDetailsModel>) objTicketDetails;
				System.out.println("Ticket Details:" + objTicketDetails);
				AppData.ticketDetailsList = ticketDetailsList;

				updateTinToMobifin(tinForMobifin, blockKeytoConfirm,
						TicketDetailsModel.getTicketJSON());
				// Intent TicketDetailsIntent = new Intent(
				// PinConformActivity.this,
				// TicketBookingSummaryScreen.class);
				// TicketDetailsIntent.putExtra("TAG", "FromPinConfirm");
				// startActivity(TicketDetailsIntent);

			}
		};

		// TODO Auto-generated method stub
		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager.getTicketDetails(PinConformActivity.this,
				ticketDetailsResponseFromSeatSeller, AppData.CONSUMERKEY,
				AppData.SECRETKEY, AppData.BASESEATURL + "/ticket?tin="
						+ (String) objTicketNo, "TicketDetails");
	}

	public void updateTinToMobifin(String tinForMobifin,
			String blockKeytoConfirm, String PassengerJSON) {

		ResponseListener tinUpdateResponseListener = new ResponseListener() {
			@Override
			public void onResponse(Object object) {
				// TODO Auto-generated method stub

				try {
					JSONObject mobifinResponse = new JSONObject((String) object);
					String responseCode, responseDesc;
					responseCode = mobifinResponse.getString("ResponseCode");
					responseDesc = mobifinResponse
							.getString("ResponseDescription");
					if (responseCode.equals("000")
							&& responseDesc.equals("Successful")) {

						Intent TicketDetailsIntent = new Intent(
								PinConformActivity.this,
								TicketBookingSummaryScreen.class);
						TicketDetailsIntent.putExtra("TAG", "FromPinConfirm");
						startActivity(TicketDetailsIntent);

					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				;

			}
		};

		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager.notifyTicketToMobifin(PinConformActivity.this,
				tinForMobifin, blockKeytoConfirm, PassengerJSON,
				tinUpdateResponseListener);

	}
}
